import baseUrl from './domain'
// #ifdef MP-WEIXIN
baseUrl = baseUrl + '/api'
// #endif

// console.log(baseUrl, 'baseurl')
let i = 0;
export const $request = (
	url,
	data = {},
	method = 'GET',
	isDomain = true,
	header = {
		'content-type': 'application/json'
	}
) => {
	// i++;
	if (isDomain) {
		const token = uni.getStorageSync('token')
		// console.log(token)
		header['token'] = token
		header['Authorization'] = token
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/${url}`,
			data,
			method,
			header,
			success: res => {
				i++;
				if (res.data.code == 200 || res.data.code == '000') {
					resolve(res.data)
				} else if (+res.data.code == 1001 || (+res.data.code == 4) || (+res.data.code ==
						5) || (+res.data.code ==
						-1)) {

					uni.showToast({
						title: res.data.message,
						icon: 'none'
					})
				} else if ((res.data.code == '002' || res.data.code == '001' || res.data.code ==
						'1003' || res.data.code ==
						'1005') && i <= 1) {
					uni.navigateTo({
						url: '/pages/login/index'
					})
				} else if (res.data.code == '003') {
					uni.showToast({
						title: res.data.message,
						icon: 'none'
					})
				} else if (res.data.code == 1000) {
					// console.log("2222222", res.data)
				} else if (res.data.code == 1013 || res.data.code == 1004 || res.data.code ==
					1005) {
					// uni.reLaunch({
					// 	url: '/pages/selectStore/index'
					// })
					reject(res.data)
				}
				//else if(res.data.code == 1000) {
				// 	uni.
				// }
				else {
					if (res.statusCode == 502 && i <= 1) {
						// uni.navigateTo({
						// 	url: '/pages/login/index'
						// })
					}
					// uni.showLoading({
					// 	title: "502 Bad Gateway",
					// });
					// console.log(res.statusCode)
					wx.showToast({
						title: res.data.errMsg,
						icon: 'none'
					})
					reject(res.data)
				}
			},
			fail: error => {
				// debugger
				uni.getStorage({
					key: 'errCode',
					success: function(res) {
						if (+res.data == 600001) {
							uni.showLoading({
								title: "网络已断开,请连接网络",
							});
						}
					}
				});
				reject(error)
			}
		})
	})
}


export const $get = (url, data, isDomain) => {
	return $request(url, data, 'GET', isDomain)
}

export const $post = (url, data, isDomain) => {
	return $request(url, data, 'POST', isDomain)
}